#include "def.h"
#include "2440addr.h"
#include "2440lib.h"
#include "POLUART.H"

#define REQCNT 30
#define ADCPRS 9	//YH 0627
#define LOOP 1

void __irq AdcTsAuto(void);

int count=0;
volatile int xdata, ydata;

void ToutchScreenInit(void)
{
	rADCDLY=50000;                  //Normal conversion mode delay about (1/3.6864M)*50000=13.56ms
	rADCCON=(1<<14)+(ADCPRS<<6);
	rADCTSC=0xd3;  //Wfait,XP_PU,XP_Dis,XM_Dis,YP_Dis,YM_En
	pISR_ADC = (int)AdcTsAuto;
	rINTSUBMSK = rINTSUBMSK & (~(BIT_SUB_TC));
	rINTMSK= rINTMSK & (~(BIT_ADC));	
}  

void __irq AdcTsAuto(void)
{	

	if(rADCDAT0&0x8000)
    {
		rADCTSC &= 0xff;			// Set stylus down interrupt bit
    }
    		
	rADCTSC=(1<<3)|(1<<2);         //Pull-up disable, Seq. X,Y postion measure.
	rADCCON|=0x1;                   //start ADC
	
	while(  rADCCON & 0x1);			//check if Enable_start is low
	while(!(rADCCON & 0x8000));     //check if EC(End of Conversion) flag is high, This line is necessary~!!
	while(!(rSRCPND & (BIT_ADC)));  //check if ADC is finished with interrupt bit

	xdata=(rADCDAT0&0x3ff);
	ydata=(rADCDAT1&0x3ff);
	
	rSUBSRCPND |= BIT_SUB_TC;
	ClearPending(BIT_ADC);
		 
	rADCTSC = 0xd3;    			//Waiting for interrupt
	rADCTSC = rADCTSC|(1<<8);	// Detect stylus up interrupt signal	
	
	while(1)					//to check Pen-up state
	{
		if(rSUBSRCPND & (BIT_SUB_TC))//check if ADC is finished with interrupt bit
			break;
	}	
	
	Uart0Printf("count=%03d  XP=%04d, YP=%04d\r\n", count++, xdata, ydata);
 
	rADCTSC    =  rADCTSC&~(1<<8); // Detect stylus Down interrupt signal.
    rSUBSRCPND |= BIT_SUB_TC;
	ClearPending(BIT_ADC);

}